<?php

class AdminController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/lefty';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('view','update','changePassword','viewProfile','forgotPassword','profit','viewProfit','printToExel'),
				'users'=>array('@'),
		),

		array('deny',  // deny all users
				'users'=>array('*'),
		),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView()
	{
		$admin=Admin::model()->find();
		$this->render('view',array(
			'model'=>$admin,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Admin();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Admin']))
		{
			$model->attributes=$_POST['Admin'];
			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$password=$model->password;
		$model->password='';

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Admin']))
		{
			$model->attributes=$_POST['Admin'];
			$valid=$model->validate();
				
			if ($password!=Admin::model()->hashPassword($model->password)){
				$model->addError('password', 'The password is not correct');
				$model->new_password='';
				$model->new_password_repeat='';
				$valid=false;
			}
				
			if ($valid){
				if($model->save())
				$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Admin');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Admin('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Admin']))
		$model->attributes=$_GET['Admin'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Admin::model()->findByPk($id);
		if($model===null)
		throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='admin-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	/**
	 * Perform changing password operation
	 */
	public function actionChangepassword()
	{
		$model = new AdminChangePassword();
		if (isset(Yii::app()->user->id))
		{
			$admin = Admin::model()->findByPk(Yii::app()->user->id);
			if(isset($_POST['AdminChangePassword']))
			{
				$model->attributes=$_POST['AdminChangePassword'];

				if($admin->password!=Admin::model()->hashPassword($model->oldPassword))
				{
					$model->addError('oldPassword', 'Your password is not correct');
				}
				else
				{
					if(isset($_POST['Admin'])){
						$admin->attributes=$_POST['Admin'];
						$admin->password=Admin::model()->hashPassword($model->newPassword);
						if ($admin->validate()){
							$admin->save();
							$this->redirect(array('viewProfile','id'=>$admin->id));
						}
					}
				}
			}
			else
			{
				$model->email=$admin->email;
			}
			// render
			$this->render('changePassword',array('model'=>$model,'admin'=>$admin));
		}
		else
		{
			$this->render('site/index');
		}
	}

	public function actionViewProfile($id)
	{
		if (isset($id))
		{
			$model=Admin::model()->findByPk($id);
			$this->render('profile',array('data'=>$model));
		}
		else
		{
			$this->render('site/index');
		}
	}

	public function actionForgotPassword()

	{
		$message = new YiiMailMessage();

		$newpassword=mt_rand();
		$subject='Your new password is:'.$newpassword;
		$message->setTo(
		array( Yii::app()->params['adminEmail']=>'admin'));
		$message->setFrom(array('nguyentai1112@gmail.com'=>'admin'));
		$message->setSubject('Password recovery');
		$message->setBody($subject);

		$numsent =Yii::app()->mail->send($message);
		if ($numsent){
			$admin=Admin::model()->find();
			$admin->password=Admin::model()->hashPassword($newpassword);
			Yii::app()->user->setFlash('forgotPassword',
            'Your new password has been sent to your email.');
		}
		else
		Yii::app()->user->setFlash('forgotPassword',
            'Error occured,Please try again.');
			

		$this->render('forgotPassword');
	}
	///
	public function actionProfit(){
		if (isset($_POST['Profit'])){
			$this->redirect(array('printToExel','start_date'=>$_POST['Profit']['start_date'],'end_date'=>$_POST['Profit']['end_date']));
		}
		$this->render('profit');
	}

	public function actionviewProfit(){
		if (isset($_POST['start_date'])&&isset($_POST['end_date'])){
			$start_date=$_POST['start_date'];
			$end_date=$_POST['end_date'];

			if (strtotime($start_date)<=strtotime($end_date)){
				$condition='date_received BETWEEN "'.$start_date.'" AND "'.$end_date.'"';
				$order=Order::model()->findAll($condition.' AND status IN(1,2)' );
				$cash=Cash::model()->findAll($condition);
				$customerCheque=Cheque::model()->findAll($condition.' AND type=1');
				$supplierCheque=Cheque::model()->findAll($condition.' AND type=2');
				$fromCustomerCredit=Credit::model()->findAll($condition.' AND type=1');
				$toCustomerCredit=Credit::model()->findAll($condition.' AND type=2');
				$row_num=max(count($order),count($cash),count($customerCheque),count($supplierCheque),count($fromCustomerCredit),count($toCustomerCredit));
				$this->renderPartial('_form_profit',array('rows'=>$row_num,'order'=>$order,'cash'=>$cash,'customerCheque'=>$customerCheque,'supplierCheque'=>$supplierCheque,'fromCustomerCredit'=>$fromCustomerCredit,'toCustomerCredit'=>$toCustomerCredit));
			}
		}

	}
	public function actionprintToExel($start_date,$end_date){
		$condition='date_received BETWEEN "'.$start_date.'" AND "'.$end_date.'"';
		$order=Order::model()->findAll($condition.' AND status IN(1,2)' );
		$cash=Cash::model()->findAll($condition);
		$customerCheque=Cheque::model()->findAll($condition.' AND type=1');
		$supplierCheque=Cheque::model()->findAll($condition.' AND type=2');
		$fromCustomerCredit=Credit::model()->findAll($condition.' AND type=1');
		$toCustomerCredit=Credit::model()->findAll($condition.' AND type=2');
		$row_num=max(count($order),count($cash),count($customerCheque),count($supplierCheque),count($fromCustomerCredit),count($toCustomerCredit));

		$order_total=0;
		$cash_total=0;
		$supplier_checque_total=0;
		$customer_cheque_total=0;
		$from_credit_total=0;
		$to_credit_total=0;
		$data = array();
		$header=array('Total Order received',
		'Cash receivable',
		'Supplier Cheque',
		'Customer Cheque',
		'To Customer Credit',
		'From Customer Credit');
		$data[]=$header;
		//add data
		for ($i=0;$i<$row_num;$i++){
			$row_data=array();
			if (isset($order[$i])){
				$row_data[]=$order[$i]->invoice.'($'.$order[$i]->price.')';
				$order_total+=$order[$i]->price;
			}
			else {
				$row_data[]='-';
			}

			if (isset($cash[$i])){
				$row_data[]=$cash[$i]->invoice.'($'.$cash[$i]->amount.')';
				$cash_total+=$cash[$i]->amount;
			}
			else {
				$row_data[]='-';
			}

			if (isset($supplierCheque[$i])){
				$row_data[]=$supplierCheque[$i]->invoice.'($'.$supplierCheque[$i]->amount.')';
				$supplier_checque_total+=$supplierCheque[$i]->amount;
			}
			else {
				$row_data[]='-';
			}

			if (isset($customerCheque[$i])){
				$row_data[]=$customerCheque[$i]->invoice.'($'.$customerCheque[$i]->amount.')';
				$customer_cheque_total+=$customerCheque[$i]->amount;
			}
			else {
				$row_data[]='-';
			}



			if (isset($fromCustomerCredit[$i])){
				$row_data[]=$fromCustomerCredit[$i]->invoice.'($'.$fromCustomerCredit[$i]->amount.')';
				$from_credit_total+=$fromCustomerCredit[$i]->amount;
			}
			else {
				$row_data[]='-';
			}

			if (isset($toCustomerCredit[$i])){
				$row_data[]=$toCustomerCredit[$i]->invoice.'($'.$toCustomerCredit[$i]->amount.')';
				$to_credit_total+=$toCustomerCredit[$i]->amount;
			}
			else {
				$row_data[]='-';
			}

			$data[]=$row_data;
		}
		//add total
		$total_row=array('Total: $'.$order_total,'Total: $'.$cash_total,'Total: $'.$supplier_checque_total,'Total: $'.$customer_cheque_total,'Total: $'.$from_credit_total,'Total: $'.$to_credit_total);
		$total=$order_total+$cash_total-$supplier_checque_total-$customer_cheque_total-$to_credit_total+$from_credit_total;
		$data[]=$total_row;
		$data[]=array('','','','Profit and Loss: $'.$total);
		Yii::import('application.extensions.phpexcel.JPhpExcel');
		$xls = new JPhpExcel('UTF-8', false, 'My Test Sheet');

		/*
		 $workbook =Yii::app()->excel;
		 $sheet = $workbook->getActiveSheet();
		 $sheet->getColumnDimension('A')->setWidth(100);
		 $sheet->getColumnDimension('B')->setWidth(20);
		 $sheet->getColumnDimension('C')->setWidth(500);
		 $sheet->setCellValue('A1','ddd');
		 $writer = new PHPExcel_Writer_Excel2007($workbook);
		 $writer->save('tai.xls');
		 */
		$xls->addArray($data);
		$xls->generateXML('Profit_and_Loss');
	}

}
